<?php

namespace app\api\controller;

use app\api\model\Setting as SettingModel;

class Face extends Controller
{

    public function faceVerify($idcard, $name, $base)
    {
        $values = SettingModel::getItem('h5home');
        if (empty($values['is_face'])) {
            return $this->renderError('人脸验证已关闭！');
        }

        if ($values['is_face'] == 1) {
            return $this->renderSuccess('验证通过');
        }

        if (empty($values['face_key'])) {
            return $this->renderError('未配置人脸信息！');
        }
        $base = str_replace('data:image/jpeg;base64,', '', $base);
        $appcode = $values['face_key'];
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => "https://vidface.market.alicloudapi.com/lundear/idface",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => "idcard={$idcard}&name={$name}&image={$base}&liveck=1",
            CURLOPT_HTTPHEADER => [
                "content-type: application/x-www-form-urlencoded; charset=UTF-8",
                "Authorization:APPCODE " . $appcode
            ],
        ]);
        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);
        if ($err) {
            return $this->renderError("Error #:" . $err);
        } else {
            $res = json_decode($response, true);
            if (empty($res)) {
                return $this->renderError('请检查人脸配置是否正确');
            }
            if ($res['code'] === null) {
                return $this->renderError('当前访问人数过多，请稍后再试');
            }
            if ($res['code'] == 0) {
                return $this->renderSuccess('验证通过');
            } else {
                if ($res['code'] == 11) {
                    $res['desc'] = '未检测到活体！请勿对照片进行翻拍，截取等方式进行拍照验证';
                }
                return $this->renderError($res['desc']);
            }
        }
    }

}
